import { createSlice, type PayloadAction } from "@reduxjs/toolkit";

interface musicDetail{
    id:string|number,
    name:string,
    artist:string,
    coverUrl?:string,
    time:number|null,
    url:string,
    curTime?:number|null,
}

interface musicList{ 
    id:string|number,
    name:string,
    artist:string,
}

interface MusicState {
    actMusicInfo: musicDetail | null;
    playList: musicList[];
    musicMode: number; // 1: 顺序播放 2: 随机播放 3: 单曲循环
}

const initialState: MusicState = {
    actMusicInfo: null,
    playList: [],
    musicMode: 1,
}

const musicStore = createSlice({
    name: "music",
    initialState,
    reducers: {
        setActMusicInfo: (state, action: PayloadAction<musicDetail>) => {
            state.actMusicInfo = null
            state.actMusicInfo = action.payload;
        },
        setPlayList: (state, action: PayloadAction<musicList[]>) => {
            state.playList = action.payload;
        },
        setMusicMode: (state, action: PayloadAction<number>) => {
            state.musicMode = action.payload;
        },
        setActCurTime: (state, action: PayloadAction<number>) => {
            if(state.actMusicInfo){
                state.actMusicInfo.curTime = action.payload;
            }
        },
        removeMusic: (state, action: PayloadAction<string|number>) => { 
            state.playList = state.playList.filter(item => item.id !== action.payload);
        },
        clearPlayList: (state) => { 
            state.playList = [];
        },
        addToNextPlay: (state, action: PayloadAction<musicList>) => { 
            const index = state.playList.findIndex(item => item.id === state.actMusicInfo?.id);
            
            state.playList = state.playList.filter(item => item.id !== action.payload.id);
            if(index !== -1){
                state.playList.splice(index + 1, 0, action.payload);
            }else{
                state.playList.unshift(action.payload);
            }
        },
    },
});


const musicReducer = musicStore.reducer

export const {
    setActMusicInfo,
    setPlayList,
    setMusicMode, 
    setActCurTime,
    removeMusic,
    addToNextPlay,
    clearPlayList} = musicStore.actions
export default musicReducer;